package feng.demo.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;

import org.springframework.web.filter.CorsFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
//配置拦截路径
public class SatokenConfig implements WebMvcConfigurer {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handler -> {
            SaRouter.match("/user/**", r -> StpUtil.checkLogin());//登录才能访问
            SaRouter.match("/adm/**",r -> StpUtil.checkRoleOr("adm"));//需要登录管理员才能访问
            SaRouter.match("/cus/**",r -> StpUtil.checkRoleOr("cus"));
            SaRouter.match("/mer/**",r -> StpUtil.checkRoleOr("mer"));
        }))
                .excludePathPatterns("/public/**")//无需登录就能访问
                .addPathPatterns("/**").excludePathPatterns("/static/**","/assets/**","/*.html");//无需登录，就可以访问);
    }
    @Bean
    public SatokenExceptionResolver satokenExceptionResolver(){
        return new SatokenExceptionResolver();
    }

//    打开跨域
    @Bean
    public CorsFilter corsFilter(){
        CorsConfiguration config = new CorsConfiguration();
        // 允许所有域名进行跨域调用
        config.addAllowedOriginPattern("*");
        // 允许任何请求头
        config.addAllowedHeader("*");
        // 允许任何方法（POST、GET等）
        config.addAllowedMethod("*");
        // 允许携带凭证
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
